package com.bidevalution.business.function;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Random;

import com.googlecode.aviator.runtime.function.AbstractFunction;
import com.googlecode.aviator.runtime.function.FunctionUtils;
import com.googlecode.aviator.runtime.type.AviatorObject;
import com.googlecode.aviator.runtime.type.AviatorString;

public class RandomPortionFunction extends AbstractFunction{
	private FunctionInitializer functionInitializer;
	public RandomPortionFunction(FunctionInitializer functionInitializer) {
		super();
		this.functionInitializer = functionInitializer;
	}
	@Override
	public AviatorObject call(Map<String, Object> env, AviatorObject arg1, AviatorObject arg2, AviatorObject arg3, AviatorObject arg4) {

		BigDecimal minBigDecimal = new BigDecimal(arg1.getValue(env).toString());
		BigDecimal maxBigDecimal = new BigDecimal(arg2.getValue(env).toString());
		int portionNum = Integer.valueOf(arg3.getValue(env).toString());
		int scale = Integer.valueOf(arg4.getValue(env).toString());
		BigDecimal divisorValue = maxBigDecimal.subtract(minBigDecimal).divide(new BigDecimal(portionNum), scale,RoundingMode.HALF_UP);
		List<BigDecimal> portionValues = new LinkedList<BigDecimal>();
		BigDecimal tempValue = minBigDecimal;
		portionValues.add(tempValue);
		for (int i = 1; i <= portionNum; i++) {
			tempValue = tempValue.add(divisorValue);
			portionValues.add(tempValue);
		}
		return new AviatorString(String.valueOf(portionValues.get(new Random().nextInt(portionNum + 1))));
	}
	@Override
	public String getName() {
		return "randomPortion";
	}

}
